from django import forms
from .models import *
import pandas as pd

class EformSchemaForm(forms.Form):
    """EformSchemaForm definition."""
    class Meta:
        fields='_all__'
    
    # TODO: Define form fields here

class copySchemaForm(forms.Form):
    SCHEMA_CHOICES=EformSchema.objects.all().order_by('formNo')
    formNo = forms.ModelChoiceField(label='COPY FORM', queryset=SCHEMA_CHOICES)

class importCSVForm(forms.Form):
    didofile = forms.FileField(label='DIDO CSV', required=False, widget=forms.FileInput(attrs={'accept': ".csv"}))
    senvfile = forms.FileField(label='SENV CSV', required=False, widget=forms.FileInput(attrs={'accept': ".csv"}))
    s24vfile = forms.FileField(label='S24V CSV', required=False, widget=forms.FileInput(attrs={'accept': ".csv"}))

    def uploadData(self, eform, *args, **kwargs):
        dido_msg=senv_msg=s24v_msg=""

        DIDO_header=["date", "absolute", "car no.", "odometer", "result", "failled", "d1", "d2", "d3"]
        SENV_header=["date", "absolute", "car no.", "odometer", "result", "failled", "c1", "c2", "c3", "c4"]
        S24V_header=["date", "absolute", "car no.", "odometer", "result", "failled", "24v"]

        # check DIDO file
        if self.cleaned_data['didofile']:
            df = pd.read_csv(self.cleaned_data['didofile'])
            df.columns = [c.strip().lower() for c in df.columns]
            if all(item in DIDO_header for item in df.columns.values.tolist()):
                dido_msg="Imported DIDO file"

                # skip first line
                for id, row in df[1:].iterrows():
                    dido_index=str(id)
                    eform.formData['dido_date_'+dido_index]=str(datetime.datetime.strptime(row["date"], '%m/%d/%y')) if row["date"] else ''
                    eform.formData['dido_time_'+dido_index]=row["absolute"]
                    eform.formData['dido_carno_'+dido_index]=row["car no."].strip() if row["car no."] else ''
                    eform.formData['dido_failled_'+dido_index]=row["failled"].strip() if row["failled"] else ''
                    eform.formData['dido_result_'+dido_index]=row["result"].strip().lower() if row["result"] else ''
                    eform.formData['dido_d1_'+dido_index]=row["d1"]
                    eform.formData['dido_d2_'+dido_index]=row["d2"]
                    eform.formData['dido_d3_'+dido_index]=row["d3"]
            else:
                dido_msg="Incorrect DIDO file header"

        
        # check SENV file
        if self.cleaned_data['senvfile']:
            df = pd.read_csv(self.cleaned_data['senvfile'])
            df.columns = [c.strip().lower() for c in df.columns]
            if all(item in SENV_header for item in df.columns.values.tolist()):
                senv_msg="Imported SENV file"

                # skip first line
                for i_s, row in df[1:].iterrows():
                    senv_index=str(i_s)
                    eform.formData['senv_date_'+senv_index]=str(datetime.datetime.strptime(row["date"], '%m/%d/%y')) if row["date"] else ''
                    eform.formData['senv_time_'+senv_index]=row["absolute"]
                    eform.formData['senv_carno_'+senv_index]=row["car no."].strip() if row["car no."] else ''
                    eform.formData['senv_failled_'+senv_index]=row["failled"].strip() if row["failled"] else ''
                    eform.formData['senv_result_'+senv_index]=row["result"].strip().lower() if row["result"] else ''
                    eform.formData['senv_c1_'+senv_index]=row["c1"]
                    eform.formData['senv_c2_'+senv_index]=row["c2"]
                    eform.formData['senv_c3_'+senv_index]=row["c3"]
                    eform.formData['senv_c4_'+senv_index]=row["c4"]
            
                senv_msg="Imported SENV file"
            else:
                senv_msg="Incorrect SENV file header"


        # check S24V file
        if self.cleaned_data['s24vfile']:
            df = pd.read_csv(self.cleaned_data['s24vfile'])
            df.columns = [c.strip().lower() for c in df.columns]
            if all(item in S24V_header for item in df.columns.values.tolist()):
                s24v_msg="Imported S24V file"

                # skip first line
                for i_s, row in df[1:].iterrows():
                    s24v_index=str(i_s)
                    eform.formData['s24v_date_'+s24v_index]=str(datetime.datetime.strptime(row["date"], '%m/%d/%y')) if row["date"] else ''
                    eform.formData['s24v_time_'+s24v_index]=row["absolute"]
                    eform.formData['s24v_carno_'+s24v_index]=row["car no."].strip() if row["car no."] else ''
                    eform.formData['s24v_failled_'+s24v_index]=row["failled"].strip() if row["failled"] else ''
                    eform.formData['s24v_result_'+s24v_index]=row["result"].strip().lower() if row["result"] else ''
                    eform.formData['s24v_24v_'+s24v_index]=row["24v"]

            else:
                s24v_msg="Incorrect S24V file header"

        eform.save()
        msg=[dido_msg, senv_msg, s24v_msg]

        return msg
                


                # elif all(item in dido_headers for item in SENV_header):
                #     msg="Imported SENV file"
                # elif all(item in dido_headers for item in S24V_header):
                #     msg="Imported S24V file"